package com.sea.base.utils.vc

import android.content.Context
import android.content.ContextWrapper
import androidx.annotation.RequiresApi
import com.sea.base.ext.global.singleApplication
import com.sea.base.ext.global.throwIfDebug
import com.sea.base.ext.view.realContext
import java.lang.reflect.Field

/**
 * 预埋一个代理Context，后面布局优化会用到
 */
class ContextProxy @JvmOverloads constructor(base: Context = singleApplication) : ContextWrapper(base) {
    companion object {
        val mBaseField: Field?

        init {
            var f: Field?
            try {
                f = ContextWrapper::class.java.getDeclaredField("mBase")
                f.isAccessible = true
            } catch (e: Exception) {
                "反射出错，这很能是因为api政策限制".throwIfDebug(e)
                f = null
            }
            mBaseField = f
        }

    }

    @Deprecated("见[setRealContext]", ReplaceWith("setRealContext"))
    @RequiresApi(999)
    override fun attachBaseContext(base: Context) {
        super.attachBaseContext(base)
    }

    @RequiresApi(999)
    @Deprecated("见[getRealContext]", ReplaceWith("getRealContext"))
    override fun getBaseContext(): Context {
        return super.getBaseContext()
    }

    var realContext: Context
        get() = baseContext.realContext
        set(base) {
            if (mBaseField == null || base == this) {
                return
            }
            mBaseField[this] = base.realContext
        }
}